package hn.cch.fdfs;

import hn.cch.util.FileUtil;
import hn.cch.util.StreamUtil;
import hn.cch.util.StringUtil;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class FdfsUtil {

    private static final Logger logger = LoggerFactory.getLogger(FdfsUtil.class);


    private static TrackerClient trackerClient = null;
    private static TrackerServer trackerServer = null;
    private static StorageServer storageServer = null;
    private static StorageClient storageClient = null;

    public static void main(String[] args) {

        initFdfs();

        // String localPath = "C:\\Users\\CCH\\Desktop\\0.png";
        //
        // String[] uploadResult = uploadFile(localPath);
        //
        // String localName = "C:\\Users\\CCH\\Desktop\\1.png";
        // File localFile = downloadFile(uploadResult, localName);
        //
        // String groupName = uploadResult[0];
        // String remotePath = uploadResult[1];
        // FileInfo fileInfo = getFileInfo(groupName, remotePath);

        // String groupName = uploadResult[0];
        // String remotePath = uploadResult[1];
        // int del = deleteFile(groupName, remotePath);


        String fileName = "./binlog.000";
        String fileText = StringUtil.fromBytes(FileUtil.toBytes(StreamUtil.toInput(new File(fileName))));
        logger.info("fileText:\r\n{}", fileText);
        String[] texts = fileText.split("\n");

        String groupName = "group1";
        for (int i = 0; i < texts.length; i++) {
            String line = texts[i];
            String[] lines = line.split(" ");
            String remotePath = lines[lines.length - 1];
            int deleteFlag = deleteFile(groupName, remotePath);
            logger.info("remotePath:{}|deleteFlag:{}", remotePath, deleteFlag);
        }

        closeFdfs();
    }


    public static void initFdfs() {
        String confPath = "fdfs_client.conf";
        try {
            ClientGlobal.init(confPath);
            logger.info("init");
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = null;
            storageClient = new StorageClient(trackerServer, storageServer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

    }


    public static void closeFdfs() {
        try {
            if (trackerServer != null) {
                trackerServer.close();
            }
            if (storageServer != null) {
                storageServer.close();
            }
            logger.info("close");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String[] uploadFile(String localPath) {
        try {


            //String localPath = "C:\\Users\\CCH\\Desktop\\1.jpg";
            File localFile = new File(localPath);


            String fileName = localFile.getName();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);

            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", fileName);

            byte[] fileBytes = FileUtil.toBytes(StreamUtil.toInput(localFile));
            String[] uploadResult = storageClient.upload_file(fileBytes, fileType, metaList);

            logger.info("uploadResult : {}", Arrays.asList(uploadResult));

            return uploadResult;
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File downloadFile(String[] uploadResult, String localPath) {
        try {
            //String[] uploadResult = {"group1", "M00/00/00/wKgKmV6odSeAUccHAATeRirHhBo014.jpg"};
            if (uploadResult.length < 2){
                return null;
            }

            String groupName = uploadResult[0];
            String remotePath = uploadResult[1];
            logger.info("groupName={}|remotePath={}", groupName, remotePath);

            byte[] fileBytes = storageClient.download_file(groupName, remotePath);

            //String localPath = "C:\\Users\\CCH\\Desktop\\2.jpg";
            File localFile = new File(localPath);

            FileUtil.fromBytes(StreamUtil.toOutput(localFile, false), fileBytes);

            logger.info("downloadFile : " + localFile.exists());

            return localFile;

        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int deleteFile(String groupName, String remotePath) {
        try {
            //String[] uploadResult = {"group1", "M00/00/00/wKgKmV6odSeAUccHAATeRirHhBo014.jpg"};
            // if (uploadResult.length < 2){
            //     return null;
            // }
            // String groupName = uploadResult[0];
            // String remotePath = uploadResult[1];
            logger.info("groupName={}|remotePath={}", groupName, remotePath);



            int del = storageClient.delete_file(groupName, remotePath);
            return del;
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return -9;
    }

    public static FileInfo getFileInfo(String groupName, String remotePath) {
        try {
            //String[] uploadResult = {"group1", "M00/00/00/wKgKmV6odSeAUccHAATeRirHhBo014.jpg"};
            // if (uploadResult.length < 2){
            //     return null;
            // }
            // String groupName = uploadResult[0];
            // String remotePath = uploadResult[1];
            //M00/00/00/wKgKmV6kwh2AO_sUAATeRirHhBo096.jpg
            logger.info("groupName={}|remotePath={}", groupName, remotePath);


            FileInfo fileInfo = storageClient.get_file_info(groupName, remotePath);

            return fileInfo;

        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return null;
    }



}
